<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Classe Model dalla quale ereditano tutte le calssi di tipo model
 *
 * @author andrea
 */
class Model_vidwiz {

    
    public $installationFields;
    public $allowedMIMEs;
    public $tableName;
    
    /**
     *
     * @return array i campi della tabella per l'installazione
     */
    function getInstallationFields(){
        return $this->installationFields;
    }
    
    


    /**
     *
     * @return string nome della tabella per le immagini
     */
    function getInstallationTableName(){
        return $this->tableName;
    }
    
  /** 
   * Funzione che elabora le query per creare tabelle nel database
   * @param string $tableName Nome della tabella da creare
   * @param array $fields Array dove ogni riga è un array contenente 
   *          [0]->nome del campo 
   *          [1]->tipo del campo
   *          [2]->opzioni linguaggio MySQL
   * @return string query di creazione
   */
    public function createQuery($tableName,$fields){
        $create = "CREATE TABLE ".$tableName."(";
        $length = count($fields);
        foreach ($fields as $key => $value) {
            $create .= "$value[0] ".$value[1]." ".$value[2];
            if($key < $length-1) 
                $create .= ", ";
            else
                $create .= ")";
        }
     return $create;
    }
    
    /**
     * Funzione che elabora query atte a eliminare tabelle nel database
     * @param string $tableName Nome della tabella da eliminare
     * @return string $query la query per l'eliminazione
     */
    public function dropTable($tableName){
        $query = "DROP TABLE IF EXISTS ".$tableName;
        return $query;
        
    }
    
    
    public function countEntries($table,$where = false){
        global $wpdb;
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $query = "SELECT COUNT(*) FROM ".$table;
        if($where != false){
            $length = count($where);
            $query .= " WHERE ";
            if($join != false)
                foreach($join as $key => $value){
                $query .= $value[0]."=".$value[1];
                $query .= " AND ";
            }
            foreach($where as $key => $value){
                if(!preg_match("/[INin]/", $value[1]))
                    $query .= $value[0].$value[1]."'".$value[2]."'";
                else
                    $query .= $value[0].$value[1].$value[2];
                if($key < $length-1) 
                    $query .= " AND ";
            }
        }
        
        $count = $wpdb->get_var($query);
        return $count;
    }
    
    public function countEntriesWithLimits($table,$fromLimit,$howMany){
        global $wpdb;
        $query = "SELECT COUNT (*) FROM ".$table." LIMIT ".$fromLimit;
        if($howMany != false)
            $query .= ",".$howMany;
        return $wpdb->get_var($query);
    }
    
    public function avgQuery($table,$fieldAvg,$where = false){
        $debug=  USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $query = "SELECT AVG(".$fieldAvg.") as average ";
        $query .= " FROM ".$table;
        
        if($where != false){
            $query .= " WHERE ";
            foreach($where as $key => $value){
                if(!preg_match("/[INin]/", $value[1]))
                    $query .= $value[0].$value[1]."'".$value[2]."'";
                else
                    $query .= $value[0].$value[1].$value[2];
                if($key < $length-1) 
                    $query .= " AND ";
            }
        }
        return $query;
    }

        /**
     *
     * @param type $from
     * @param type $where
     * @param type $select 
     */
    public function searchQuery($from,$where = false,$select = array("*"),$limit = false,$order = false,$join = false,$options = false){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $query = "SELECT ";
        $length = count($select);
        foreach($select as $key => $value){
            $query .= "$value";
            if($key < $length-1) 
                $query .= ", ";
            else
                $query .= " ";
        }
        $query .= "FROM ";
        if(!is_array($from))
            $query .= $from;
        else{
            $length = count($from);
            foreach($from as $key => $value){
                $query .= $value;
                if($key < $length-1) 
                    $query .= ", ";
            }
        }
        $length = count($where);
        $lengthj = count($join);
        if($where != false){
            $query .= " WHERE ";
            if($join != false)
                foreach($join as $key => $value){
                $query .= $value[0]."=".$value[1];
                $query .= " AND ";
            }
            foreach($where as $key => $value){
                if(!preg_match("/[INin]/", $value[1]))
                    $query .= $value[0].$value[1]."'".$value[2]."'";
                else
                    $query .= $value[0].$value[1].$value[2];
                if($key < $length-1) 
                    $query .= " AND ";
            }
        }
        
        if($options != false)
            $query .= " $options";
        if ($order != false)
            $query .= " order by ".$order;
        if($limit != false)
            $query .= " limit ".$limit." ";
        return $query;
    }
    
    public function countWhereQuery($table,$where,$howMany,$startingFrom){
        $query = "SELECT * ";
        $query .= "FROM ".$table;
        $length = count($where);
        if($where != false){
            $query .= " WHERE ";
            foreach($where as $key => $value){
                $query .= $value[0].$value[1]."'".$value[2]."'";
                if($key < $length-1) 
                    $query .= " AND ";
            }
        }
        if($limit != false)
            $query .= " limit ".$startingFrom.",".$howMany;
        return $query;
    }
    
    /**
     * Crea una query del tipo "select * from table where a="x" or b="y" ....
     * @param string $from
     * @param string $field
     * @param array $list
     * @param array $select
     * @param string $order
     * @return string la query 
     */
    public function orQuery($from,$field,$list = false,$select = array('*'),$order = false){
        $query = "SELECT ";
        $length = count($select);
        foreach($select as $key => $value){
            $query .= "$value";
            if($key < $length-1) 
                $query .= ", ";
            else
                $query .= " ";
        }
        $query .= "FROM ".$from;
        if($list != false){
        $length = count($list);
        $query .= " WHERE ";
        foreach($list as $key => $value){
            $query .= $field."="."'".$value."'";
            if($key < $length-1) 
                $query .= " OR ";
        }
        }
        if ($order != false)
            $query .= " order by ".$order;
        return $query;
        
    }
    
    /**
     * La funzione esegue la query passata come parametro
     * @global mixed $wpdb Oggetto di Wordpress per la gestione del database
     * @param string $query Query da eseguire
     */
    public function executeQuery($query){
        global $wpdb;
        $wpdb->query($query);
    }
    
    /**
     * Sposta il file nella cartella passata
     * @param string $uploadDir la cartella nella quale bisogna spostare il file
     * @param string $filename il nome del file da spostare e rinominare
     * @return bool il nome del file se non ci sono errori, false in caso di errori 
     */
    public function moveFile($uploadDir,$filename){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $check = USingleton_vidwiz::getInstances("UChecks_vidwiz");
        $file = $this->getFile($filename);
        if($file!=false){
            if($file['error'] == UPLOAD_ERR_OK and is_uploaded_file($file['tmp_name']))
            {   
                $samename = true;
                $n=0;
                while($samename==true){
                    $file = $this->renameFile($file);
                    $samename = $check->check_samename($file['name'],$uploadDir);
                    }
                move_uploaded_file($file['tmp_name'], $uploadDir.$file['name']);
                return $file['name'];
                }
                        
        }
        return false;
    }
    
    /**
     * Crea la directory passata come parametro
     * @param string $dirName percorso della directory
     * @return string il nome della cartella creata
     */
    public function createDir($dirName){
        mkdir ($dirName,0777);
        return $dirName;
    }
    
    
    /**
     * Rinomina con una stringa random il file passato per parametro
     * @param file $file Il file da rinominare
     * @param string $concatenate (opzionale) la stringa che si vuole aggiungere al nome del file
     * @return file il file rinominato 
     */
    public function renameFile($file,$concatenate = 0,$random = true){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $fileInfo = $this->getFileInfo($file);
        if($random == true){
            $seed1 = mt_rand(10e10, 10e16);
            $seed2 = mt_rand(10e10, 10e16);
            $newName = base_convert($seed1, 10, 36);
            $newName .= base_convert($seed2, 10, 36);
            
            }
        else{
            $newName = $file['name'];
        }
        if(!(is_string($concatenate)))
            $file['name'] = $newName.".".$fileInfo['extension'];
        else{
            $newName = $fileInfo['dirname']."/".$fileInfo['filename'].$concatenate.".".$fileInfo['extension'];
            rename($file, $newName);
            $file=$newName;
        } 
        
        return $file;
    }
    
    /**
     * Ritorna, se esiste, il file passato per parametro cercando all'interno 
     * dell'array $_FILE
     * @param string $filename il nome del file
     * @return mixed false se il file non esiste, il file richiesto se questo esiste 
     */
    public function getFile($filename){
        if(isset ($_FILES[$filename]))
            return $_FILES[$filename];
        else
            return false;
    }
    
    /* Rendiamo protetto il metodo per obbligare una redefinizione in una
    sottoclasse necessaria a sbloccare l'utilizzo del metodo dall'esterno.
    Più avanti per ottenere un risultato migliore useremo le Classi Astratte. */
    protected function writeInDB(){
        die(__("Errore nel server", 'vidwiz-plugin'));
    }
    
    /**
     *
     * @global array $current_user
     * @return string l'username della sessione attuale 
     */
    public function getUsername(){
        global $current_user;
        get_currentuserinfo(); 
        $username = $current_user->user_login;
        return $username;
    }


    /**
     * @global mixed $wpdb
     * @param string $query la query di ricerca da eseguire
     * @return array l'array contenente gli eventuali risultati della ricerca 
     */
    public function getRows($query) {
        global $wpdb;
        $rows = $wpdb->get_results($query,ARRAY_N);
        return $rows;
    }
    
        /**
     * @global mixed $wpdb
     * @param string $query la query di ricerca da eseguire
     * @return array l'array contenente gli eventuali risultati della ricerca (array associativo)
     */
    public function getRowsAssoc($query) {
        global $wpdb;
        $rows = $wpdb->get_results($query,ARRAY_A);
        return $rows;
    }
    
    /**
     * Ritorna la query per l'inserimento nel db a partire dall'oggetto passato
     * @param object $object l'oggetto da inserire
     * @return string la query di inserimento
     */
    public function insertQuery($object){
        $entity = USingleton_vidwiz::getInstances("Entity_vidwiz");
        $query = "INSERT INTO ".$this->tableName."(";
        $length = $entity->countObject($object);
        $index = 0;
        foreach ($object as $key => $value) {
            $index++;
            $query .= $key;
            if($index < $length) 
                $query .= ",";
        }
        $query .= ") VALUES (";
        $index = 0;
        foreach ($object as $key => $value) {
            $index++;
            $query .= "'".$value."'";
            if($index < $length) 
                $query .= ",";
        }
        $query .= ")";
        return $query;
        
    }
    
    /**
     * Crea la query per l'aggiornamento di determinati campi, in una determinata tabella
     * sotto determinate condizioni
     * @param string $table
     * @param array $valueSet i valori da aggiornare array[i]['campo'] array[i]['valore nuovo']
     * @param array $where condizioni che identificano le ennuple da aggiornare
     * @return string la query per l'update
     */
    public function updateQuery($table,$valueSet,$where){
        $query = "UPDATE ".$table." ";
        $query .= "SET " ;
        $length = count($valueSet);
        foreach ($valueSet as $key => $value) {
            $query .= $value[0]."="."'".$value[1]."'";
            if($key < $length-1)
                $query .= ",";
            else
                $query .= "";
        }
        $query .= " WHERE ";
        $length = count($where);
        foreach($where as $key => $value){
            if(!preg_match("/[INin]/", $value[1]))
                $query .= $value[0].$value[1]."'".$value[2]."'";
            else
                $query .= $value[0].$value[1].$value[2];
                if($key < $length-1) 
                    $query .= " AND ";
            }
        return $query;
    }

    /**
     *
     * @param mixed $file oggetto file o stringa (nome assoluto)
     * @return array le info sul files
     */
    public function getFileInfo($file){
        if(is_array($file))
            $path_parts = pathinfo($file['name']);
        else
            $path_parts = pathinfo($file);
        return $path_parts;
    }
    
    /**
     * dato il path assoluto, ritorna quello relativo (rispetto alla root di wordpress)
     * @global type $config
     * @param string $absPath il path assoluto
     * @return string il path relativo 
     */
    public function getAbsPath($path){
        $wordpress = USingleton_vidwiz::getInstances("UWordpress_vidwiz");
        
        global $config;
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $root = $wordpress->getWordpressSiteurl();
        $output = $root.$config['vidwiz_from_siteurl'].$path;
        return $output;
    }
    
    /**
     * Converte la data nel formato ISO
     * @param string $date mm/dd/yyyy
     */
    public function dateToISO($date){
        $date = explode("/", $date);
        $date =  $date[2]."-".$date[1]."-".$date[0];
        $date .= " 00:00:00";
        return $date;
    }
    
    /**
     *
     * @param string $date Y-m-d 00:00:00
     */
    public function dateToENG($date){
        $date = explode(" ", $date);
        $date = $date[0];
        $date = explode("-", $date);
        $date = $date[1]."/".$date[2]."/".$date[0];
        return $date;
    }


    public function createImageResized($image,$w = false,$h = false){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        if(!is_file($image))
            return false;
        list($width, $height, $type, $attr) = getimagesize($image);
        if($w != false && $h == false){
            $newHeight = round((134/(int)$width)*(int)$height);
            $newWidth = $w;
            }
        if($w == false && $h != false)
            $newHeight;
        if($w ==false && $h == false)
            return false;
        if($w != false && $h != false){
            $newWidth = $w;
            $newHeight = $h;
        }
        $thumb = imagecreatetruecolor($newWidth, $newHeight);
        $source = imagecreatefrompng($image);
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        $imageInfo = $this->getFileInfo($image);
        $filename = $imageInfo['dirname']."/".$imageInfo['filename']."_thumb.png";
        imagepng($thumb,$filename, 9);
    }
    
    public function getIdFromUsername($username){
        global $config;
        $query = $this->searchQuery($config['tables']['users'], array(array("user_login","=",$username)));
        $results = $this->getRowsAssoc($query);
        return $results[0]["ID"];
    }
    
    public function getUserDataFromId($id){
        $debug = USingleton_vidwiz::getInstances("UDebug_vidwiz");
        $data = get_userdata($id);
        return $data;
    }
    
    /*
     * @param $date string data nel formato Y-m-d H:i:s
     */
    public function getDateArray($date){
        $split1 = explode(" ", $date);
        $split2 = explode("-",$split1[0]);
        $split3 = explode(":",$split1[1]);
        $split = array_merge($split2,$split3);
        $return = array();
        $return['year'] = $split2[0];
        $return["month"] = $split2[1];
        $return['day'] = $split2[2];
        $return['hour'] = $split3[0];
        $return["minutes"] = $split3[1];
        $return["seconds"] = $split3[2];
        return $return;
    }
}
?>
